/*
 * HandleMap.cpp
 *
 *  Created: 2012-05-29
 *   Author: terry
 */

#include "stdafx.h"
#include "HandleMap.h"


HandleMap::HandleMap()
{

}

HandleMap::~HandleMap()
{

}

bool HandleMap::exists(HANDLE handle)
{
    return (find(handle) != NULL);
}

H264MediaPlayer* HandleMap::find(HANDLE handle)
{
    comn::AutoCritSec lock(m_cs);
    BaseHandleMap::const_iterator it = m_cont.find(handle);
    if (it != m_cont.end())
    {
        return it->second;
    }
    return NULL;
}

bool HandleMap::add(HANDLE handle, H264MediaPlayer* pPlayer)
{
    comn::AutoCritSec lock(m_cs);
    std::pair< BaseHandleMap::iterator, bool > result =  
        m_cont.insert(std::make_pair(handle, pPlayer));
    return result.second;
}

bool HandleMap::remove(HANDLE handle)
{
    bool done = false;
    comn::AutoCritSec lock(m_cs);
    BaseHandleMap::iterator it = m_cont.find(handle);
    if (it != m_cont.end())
    {
        m_cont.erase(it);
        done = true;
    }
    return done;
}

void HandleMap::deleteAll()
{
    comn::AutoCritSec lock(m_cs);
    BaseHandleMap::iterator it = m_cont.begin();
    for (; it != m_cont.end(); ++ it)
    {
        H264MediaPlayer* pPlayer = it->second;
        if (pPlayer)
        {
            pPlayer->close();
            delete pPlayer;
        }

        it->second = NULL;
    }
    m_cont.clear();
}
